from fastapi import FastAPI, File, UploadFile, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import uvicorn
import os
import io
from server import rps

app = FastAPI()
templates = Jinja2Templates(directory="templates")

@app.get("/", response_class=HTMLResponse)
def index(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

@app.post("/uploadfile")
async def upload_file(file: UploadFile = File(...)):
    ext = os.path.splitext(file.filename)[1].lower()
    try:
        file_bytes = await file.read()
        # 1. 清空 tendency 表
        rps.clear_current_table('tendency')
        # 2. 处理上传的文件
        if ext in [".xls", ".xlsx"]:
            rps.update_tickers_from_excel(io.BytesIO(file_bytes))
        elif ext == ".csv":
            rps.update_tickers_from_csv(io.BytesIO(file_bytes))
        elif ext == ".txt":
            rps.update_tickers_from_txt(io.BytesIO(file_bytes))
        else:
            return {"detail": "不支持的文件类型"}
        # 3. 清空 category 表
        rps.clear_current_table('category')
        # 4. 更新 category
        rps.update_category()
        # 5. 更新 rank
        rps.update_rank()
        return {"detail": "文件上传并处理成功"}
    except Exception as e:
        return {"detail": f"处理失败: {str(e)}"}

if __name__ == "__main__":
    uvicorn.run("web_server:app", host="0.0.0.0", port=8000, reload=True) 